Durable AI results and recovery
Use a Delta-capable Spark runtime. This opt-in notebook persists input rows and outcomes in a fresh caller-owned run directory; apply normal storage access and retention policies. It never creates a Lakehouse or installs storage dependencies.
Qualification is limited to the exact builds, runtimes and scenarios in the guide. These include controlled post-commit interruption and recovery across three Fabric Spark applications, with the previous context confirmed stopped before owner release. They do not establish abrupt-process-loss behavior, arbitrary-runtime support or exactly-once inference. This notebook is an operator walkthrough, not an automatic qualification test.
Without outputPath, Spark actions may repeat model calls. With outputPath, transform is eager and returns a Delta-backed DataFrame. Committed batches survive a session; uncommitted work, provider ambiguity and Spark retries can still repeat paid inference. This is not exactly-once inference.
Keep durable inference outside reusable SparkML pipelines and tuning wrappers. Each outputPath is a one-shot run directory. Pipeline.fit may run inference before fitting a downstream estimator; later PipelineModel.transform, folds or repeated calls then fail on that existing directory. Run the standalone transform below, read committed results with loadOutput, handle row errors, and give that stored DataFrame to a downstream pipeline that does not contain the durable stage. New inference jobs require fresh paths.
import os
from synapse.ml.services.ai import AIPrompt
RUN_NEW = False
RUN_READ = False
RUN_RESUME = False
# Set a unique fresh path for a new run; keep exactly this path for recovery.
# Fabric: default Lakehouse Files/... or the copied qualified ABFS path.
RUN_PATH = "Files/aiprompt/my-ticket-run"
def configured_stage():
return (
AIPrompt()
.setApiType("responses")
.setUrl(os.environ["MODEL_ENDPOINT"])
.setDeploymentName(os.environ["MODEL_DEPLOYMENT"])
.setSubscriptionKey(os.environ["MODEL_API_KEY"])
.setPromptTemplate("Summarize this ticket: {ticket}")
.setOutputCol("answer")
.setErrorCol("error")
.setUsageCol("usage")
.setRawResponseCol("raw")
.setOutputPath(RUN_PATH)
.setOutputBatchSize(2)
)
if RUN_NEW:
tickets = spark.createDataFrame(
[
(1, "Checkout is unavailable."),
(2, "Please explain my invoice."),
(3, "How do I update my address?"),
],
["ticket_id", "ticket"],
)
saved = configured_stage().transform(tickets)
assert saved.count() == 3 # Reads committed Delta, not live inference.
saved.select("ticket_id", "answer", "error").show(truncate=False)
Read from another session without model credentials
Storage identity is still required. Status derives counts from a pinned committed results version. All rows having terminal outcomes does not mean all model calls succeeded. Row errors are terminal and are not automatically resubmitted.
A new Spark session is not necessarily a new Spark application. This example does not qualify reads or recovery after a managed application restart; the managed qualification boundary above still applies.
isComplete means every row has a committed outcome; allSucceeded also requires zero row errors. These count flags can be true while state is still running and ownerToken remains present after the last batch commits. Neither flag proves task quiescence or permits owner release. Follow the stop-confirmed recovery procedure below; resume then finalizes without repeating committed rows, even when no rows are pending.
AIPrompt.load(stagePath) restores a saved SparkML stage and its settings. AIPrompt.loadOutput(spark, RUN_PATH) instead reads committed outcomes; a stage directory and a run directory are not interchangeable.
if RUN_READ:
status = AIPrompt.getOutputStatus(spark, RUN_PATH)
print(status)
partial_or_complete = AIPrompt.loadOutput(spark, RUN_PATH)
partial_or_complete.select("ticket_id", "answer", "error").show(truncate=False)
Recover after interruption
For Fabric, the guide records both a same-application probe and a separate controlled three-application recovery check. This notebook does not itself stop an application or prove quiescence. Its administrative sequence still requires the operator to establish that the previous application and its requests/tasks have stopped; do not infer that from a failed cell or from the prior qualification results.
Inspect status after any interruption or error, including a failed cell in the same application. Successful completion clears ownership. A driver-side batch-preparation failure also releases its matching token when all prior actions finished successfully and no new distributed work started; fix the preparation error before resuming. Cancellation, failed Spark jobs and uncertain storage outcomes retain ownership because task/request quiescence is not proven. If status still has an owner, first stop the previous Spark application and prove its requests/tasks have quiesced. A failed or disconnected notebook cell is not proof. Copy the exact token from status, and only then perform the administrative release below. A mismatched token fails; there is no automatic takeover or force flag.
Recreate the original stage class, identical non-credential request settings and output names. The concrete stage class is recorded independently of telemetry, even when telemetry is disabled or customized, so direct stages and the facade are not interchangeable recovery constructors. Stage transport settings concurrency, timeout and concurrentTimeout must also retain their original values and explicit/default bindings: they participate in the fingerprint even though Spark tuning such as spark.sql.shuffle.partitions does not. To change transport settings, start a new run with a fresh outputPath and deliberately select the rows to submit; resume cannot retune pending requests or retry committed errors. Rebind scalar credentials; rotation does not change the fingerprint. Resume uses the saved input snapshot, never a replacement DataFrame. Do not include credential columns, remote media, file IDs, previous-response IDs or provider retrieval/tool state in a durable run. Incomplete initialization must be investigated, not treated as a completed empty result.
# Deliberately not executable without an operator supplying the exact token:
# AIPrompt.releaseOutputOwner(spark, RUN_PATH,
# expectedOwnerToken='<token copied from status>', confirmStopped=True)
if RUN_RESUME:
resumed = configured_stage().resume(spark)
print(AIPrompt.getOutputStatus(spark, RUN_PATH))
resumed.select("ticket_id", "answer", "error").show(truncate=False)
Scale and operate
Before starting a run, set spark.sql.shuffle.partitions deliberately, for example spark.conf.set('spark.sql.shuffle.partitions', '8'), and tune per-partition concurrency to the model quota. Each durable batch is repartitioned to min(batch row count, spark.sql.shuffle.partitions); repartitioning the original input does not control inference parallelism after snapshot storage. Approximate in-flight requests are active batch partitions times concurrency, limited by executor slots and available rows. The Spark partition setting can change on resume, but stage transport tuning is fixed for the lifetime of a durable run. A durable batch limits rows at risk before the next atomic commit; smaller batches improve recovery granularity but incur more Delta overhead. Only bounded pending keys are collected internally, not source rows. Repeated user rows keep distinct stored identities. Inspect committed outputs instead of calling count or show on a live inference plan before writing it.
With the default handler, each active partition can create up to concurrency HTTP worker threads and buffer that many pending request/response entries. concurrency defaults to 1; explicit positive values have no additional library ceiling or executor-wide clamp. Budget for all simultaneously running partitions on each executor, including inline-media/response memory and Spark's own threads. High values can exhaust container thread/process or memory limits and cause executor loss and repeated requests. Start at the default and measure before raising it; do not carry large legacy OpenAIPrompt settings over unchanged. Choose the value before the durable run starts because changing it requires a fresh run, not resume.
The directory contains _control/, _input/ and results/; it is not automatically a catalog table. Keep the complete run together for recovery. No automatic cleanup or schema evolution is performed.
Exclude _input/ from all manual and automatic maintenance after initialization. Defer results/ OPTIMIZE and VACUUM until status is complete and has no owner. Even data-preserving results compaction between batches can stop inference and retain ownership. If that happens, follow the stop-confirmed release and resume procedure above; a failed cell alone is not proof of quiescence. Maintenance of completed results must preserve schema, row identities and outcomes, and respect Delta retention and readers of older snapshots. Never append, update or delete result rows; leave _control/ managed by the run APIs. The _input/ restriction still applies after completion. See the guide for Scala APIs, vector storage and schema nullability.